<template>
  <div class="studyContainer">
    <div class="box1">
      <div class="title">教学质量评分</div>
      <div class="chengJJL-container">
        <div class="chengJJL-item">
          <div class="chengJJL-itembox-left">
            <div class="score">
              {{ satisfiRateData.satisfi_rate || rlt.stuRankInfo.sum_score }}
              <!-- satisfi_rate属性满意度 -->
            </div>
            <img
              v-if="(satisfiRateData.ranking || rlt.stuRankInfo.ranking) && (satisfiRateData.ranking || rlt.stuRankInfo.ranking) <= 10"
              class="score-img"
              src="@/assets/images/profile/students/Good.png"
            />
            <p class="score-p">
              排名：{{ satisfiRateData.ranking || rlt.stuRankInfo.ranking }}/{{
                satisfiRateData.total_num || rlt.stuRankInfo.total_num
              }}
            </p>
          </div>
          <div class="chengJJL-itembox-right">
            <div class="flex align-center justify-between score-date">
              <div style="flex: 1">学年统计</div>

            </div>
            <div ref="chartRefA" class="chart-container"></div>
          </div>
        </div>
      </div>
    </div>
    <div class="box1">
      <div class="title">教学评价</div>
      <div class="chengJJL-container">
        <div class="chengJJL-item">
          <div class="chengJJL-itembox">
            <div class="s-title">评教评学：</div>
            <div class="flex align-center" style="height: calc(100% - 14px)" v-px-to-vw>
              <div ref="pieChartRef" class="chart-container" style="flex: 3" ></div>
              <div style="flex: 2; margin-right: 10px" v-px-to-vw>
                                 <div
                   v-for="(item, index) in satisfiDistrData.pieData"
                   :key="index"
                   class="legend flex justify-between"
                   :style="{ color: item.color }"
                 >
                   <div>
                     <div
                       class="legend-dot"
                       :style="{ background: item.color }"
                     ></div>
                     {{ item.label }}
                   </div>
                   {{ item.num }}个
                 </div>
              </div>
            </div>
          </div>
          <div class="chengJJL-itembox">
            <div class="s-title">学案评价：</div>
            <div class="flex align-center" style="height: calc(100% - 14px)" v-px-to-vw>
              <div  ref="pieChartRefA"  class="chart-container"  style="flex: 3"></div>
              <div style="flex: 2; margin-right: 10px" v-px-to-vw>
                <div class="legend-a">学案满意率</div>
                <div class="flex justify-between legend-content">
                  参与评价人数
                  <div style="color: #00d1ff">{{ xaStatisData.total_num }}人</div>
                </div>
                <div class="flex justify-between legend-content">
                  满意人数
                  <div style="color: #00ffb2">{{ xaStatisData.my_num }}人</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="box1" style="height: 40%">
      <div class="title">班级均分与超越得分</div>
      <div class="chengJJL-container">
        <div class="chengJJL-item">
          <div class="chengJJL-itembox">
            <div ref="lineChartRef" class="chart-container"></div>
          </div>
          <div class="chengJJL-itembox">
            <div ref="barChartRef" class="chart-container"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, reactive, nextTick, watch } from "vue";
import * as echarts from "echarts";
import { getSatisfiRateRanking, getXaStatis, getSatisfiDistr, getLastSixRate, getTeachingQualityEvaluation } from "@/api/teacher.js";
import { useRoute } from "vue-router";

// 获取路由实例
const route = useRoute();

// 数据缓存机制 - 避免重复请求相同教师的数据
const dataCache = new Map();

// 满意度排名数据
const satisfiRateData = reactive({
  satisfi_rate: 0,
  ranking: 0,
  total_num: 0,
});

// 学案评价数据
const xaStatisData = reactive({
  total_num: 0,
  my_num: 0,
  satisfaction_rate: 0, // 满意率百分比
});

// 满意度分布数据
const satisfiDistrData = reactive({
  pieData: [],
  satisfactionRate: 0, // 满意率百分比
});

// 学年统计数据
const yearStatData = reactive({
  chartData: [],
  xAxisData: [],
  seriesData: []
});

// 教学质量评价数据
const teachingQualityData = reactive({
  averageScores: [], // 平均分数据
  exceedScores: []   // 超越得分数据
});



// 获取满意度排名数据
const getSatisfiRateData = async () => {
  try {
    // 从路由参数获取工号
    const gh = route.query.personCode;
    if (!gh) {
      console.warn('教师工号为空，无法获取数据');
      return;
    }
    
    // 检查缓存
    const cacheKey = `satisfiRate_${gh}`;
    if (dataCache.has(cacheKey)) {
      const cachedData = dataCache.get(cacheKey);
      Object.assign(satisfiRateData, cachedData);
      return;
    }
    
    const response = await getSatisfiRateRanking(gh);
    
    if (response.code === 0 && response.data && response.data.length > 0) {
      const data = response.data[0];
      const result = {
        satisfi_rate: data.satisfi_rate,
        ranking: data.ranking,
        total_num: data.total_num
      };
      
      // 更新数据
      Object.assign(satisfiRateData, result);
      
      // 缓存数据
      dataCache.set(cacheKey, result);
    } else {
      // 如果没有数据，清空显示
      const result = {
        satisfi_rate: 0,
        ranking: 0,
        total_num: 0
      };
      Object.assign(satisfiRateData, result);
      dataCache.set(cacheKey, result);
    }
  } catch (error) {
    console.error('获取满意度排名数据失败:', error);
    // 出错时也清空显示
    const result = {
      satisfi_rate: 0,
      ranking: 0,
      total_num: 0
    };
    Object.assign(satisfiRateData, result);
  }
};

// 获取学案评价数据
const getXaStatisData = async () => {
  try {
    const gh = route.query.personCode;
    if (!gh) {
      console.warn('教师工号为空，无法获取数据');
      return;
    }
    
    // 检查缓存
    const cacheKey = `xaStatis_${gh}`;
    if (dataCache.has(cacheKey)) {
      const cachedData = dataCache.get(cacheKey);
      Object.assign(xaStatisData, cachedData);
      await nextTick();
      updateXaChart();
      return;
    }
    
    const response = await getXaStatis(gh);
    
    if (response.code === 0 && response.data && response.data.length > 0) {
      const data = response.data[0];
      const result = {
        total_num: data.total_num,
        my_num: data.my_num,
        satisfaction_rate: data.total_num > 0 ? Math.floor((data.my_num / data.total_num) * 100) : 0
      };
      
      // 更新数据
      Object.assign(xaStatisData, result);
      
      // 缓存数据
      dataCache.set(cacheKey, result);
      
      // 更新图表
      await nextTick();
      updateXaChart();
    } else {
      // 如果没有数据，清空显示
      const result = {
        total_num: 0,
        my_num: 0,
        satisfaction_rate: 0
      };
      Object.assign(xaStatisData, result);
      dataCache.set(cacheKey, result);
      
      await nextTick();
      updateXaChart();
    }
  } catch (error) {
    console.error('获取学案评价数据失败:', error);
    // 出错时也清空显示
    const result = {
      total_num: 0,
      my_num: 0,
      satisfaction_rate: 0
    };
    Object.assign(xaStatisData, result);
    
    await nextTick();
    updateXaChart();
  }
};

// 获取满意度分布数据
const getSatisfiDistrData = async () => {
  try {
    const gh = route.query.personCode;
    if (!gh) {
      console.warn('教师工号为空，无法获取数据');
      return;
    }
    
    // 检查缓存
    const cacheKey = `satisfiDistr_${gh}`;
    if (dataCache.has(cacheKey)) {
      const cachedData = dataCache.get(cacheKey);
      Object.assign(satisfiDistrData, cachedData);
      await nextTick();
      updatePieChart();
      return;
    }
    
    const response = await getSatisfiDistr(gh);
    
    if (response.code === 0 && response.data && response.data.length > 0) {
      const data = response.data;
      
      // 定义颜色映射
      const colorMap = {
        "非常满意": "#00FFB2",
        "满意": "#00FFFF", 
        "基本满意": "#FBFF0D",
        "不满意": "#FFFFFF",
        "一般": "#FBFF0D" // 将"一般"映射为"基本满意"的颜色
      };
      
      // 计算总数
      const totalNum = data.reduce((sum, item) => sum + item.num, 0);
      
      // 计算满意率（达到满意的总数除以所有总数）
      const satisfiedNum = data.reduce((sum, item) => {
        // 根据label判断是否为满意
        if (item.label === "非常满意" || item.label === "满意") {
          return sum + item.num;
        }
        return sum;
      }, 0);
      
      const satisfactionRate = totalNum > 0 ? Math.floor((satisfiedNum / totalNum) * 100) : 0;
      
      // 构建饼图数据
      const pieData = data.map(item => ({
        name: item.label,
        value: item.num,
        color: colorMap[item.label] || "#FFFFFF",
        label: item.label,
        num: item.num
      }));
      
      // 更新数据
      const result = {
        pieData: pieData,
        satisfactionRate: satisfactionRate
      };
      Object.assign(satisfiDistrData, result);
      
      // 缓存数据
      dataCache.set(cacheKey, result);
      
      // 更新图表
      await nextTick();
      updatePieChart();
    } else {
      // 如果没有数据，清空显示
      const result = {
        pieData: [],
        satisfactionRate: 0
      };
      Object.assign(satisfiDistrData, result);
      dataCache.set(cacheKey, result);
      
      await nextTick();
      updatePieChart();
    }
  } catch (error) {
    console.error('获取满意度分布数据失败:', error);
    // 出错时也清空显示
    const result = {
      pieData: [],
      satisfactionRate: 0
    };
    Object.assign(satisfiDistrData, result);
    
    await nextTick();
    updatePieChart();
  }
};

// 获取学年统计数据
const getYearStatData = async () => {
  try {
    const gh = route.query.personCode;
    if (!gh) {
      console.warn('教师工号为空，无法获取数据');
      return;
    }
    
    // 检查缓存
    const cacheKey = `yearStat_${gh}`;
    if (dataCache.has(cacheKey)) {
      const cachedData = dataCache.get(cacheKey);
      Object.assign(yearStatData, cachedData);
      await nextTick();
      updateYearChart();
      return;
    }
    
    const response = await getLastSixRate(gh);
    
    if (response.code === 0 && response.data && response.data.length > 0) {
      const data = response.data;
      
      // 处理数据，提取plan_name作为x轴，satisfi_rate作为y轴
      const xAxisData = data.map(item => item.plan_name);
      const seriesData = data.map(item => item.satisfi_rate);
      
      // 更新数据
      const result = {
        chartData: data,
        xAxisData: xAxisData,
        seriesData: seriesData
      };
      Object.assign(yearStatData, result);
      
      // 缓存数据
      dataCache.set(cacheKey, result);
      
      // 更新图表
      await nextTick();
      updateYearChart();
    } else {
      // 如果没有数据，清空显示
      const result = {
        chartData: [],
        xAxisData: [],
        seriesData: []
      };
      Object.assign(yearStatData, result);
      dataCache.set(cacheKey, result);
      
      await nextTick();
      updateYearChart();
    }
  } catch (error) {
    console.error('获取学年统计数据失败:', error);
    // 出错时也清空显示
    const result = {
      chartData: [],
      xAxisData: [],
      seriesData: []
    };
    Object.assign(yearStatData, result);
    
    await nextTick();
    updateYearChart();
  }
};

// 获取教学质量评价数据
const getTeachingQualityData = async () => {
  try {
    const teacherCode = route.query.personCode;
    if (!teacherCode) {
      console.warn('教师工号为空，无法获取数据');
      return;
    }
    
    // 检查缓存
    const cacheKey = `teachingQuality_${teacherCode}`;
    if (dataCache.has(cacheKey)) {
      const cachedData = dataCache.get(cacheKey);
      Object.assign(teachingQualityData, cachedData);
      await nextTick();
      updateLineChart();
      updateBarChart();
      return;
    }
    
    const response = await getTeachingQualityEvaluation(teacherCode);
    
    if (response.code === 0 && response.data && response.data.length > 0) {
      const data = response.data;
      
      // 按班级分组数据
      const classGroups = {};
      
      data.forEach(item => {
        const className = item.bjmc; // 班级名称
        if (!classGroups[className]) {
          classGroups[className] = [];
        }
        classGroups[className].push({
          examName: item.ksmc, // 考试名称
          averageScore: item.bjjf, // 班级均分
          exceedScore: item.cyz // 超越得分
        });
      });
      
      // 处理平均分数据 - 按考试名称分组
      const examGroups = {};
      data.forEach(item => {
        const examName = item.ksmc;
        if (!examGroups[examName]) {
          examGroups[examName] = [];
        }
        examGroups[examName].push({
          className: item.bjmc,
          averageScore: item.bjjf
        });
      });
      
      // 更新数据
      const result = {
        averageScores: examGroups,
        exceedScores: data.map(item => ({
          className: item.bjmc,
          examName: item.ksmc, // 添加考试名称
          exceedScore: item.cyz
        }))
      };
      Object.assign(teachingQualityData, result);
      
      // 缓存数据
      dataCache.set(cacheKey, result);
      
      // 更新图表
      await nextTick();
      updateLineChart();
      updateBarChart();
    } else {
      // 如果没有数据，清空显示
      const result = {
        averageScores: [],
        exceedScores: []
      };
      Object.assign(teachingQualityData, result);
      dataCache.set(cacheKey, result);
      
      await nextTick();
      updateLineChart();
      updateBarChart();
    }
  } catch (error) {
    console.error('获取教学质量评价数据失败:', error);
    // 出错时也清空显示
    const result = {
      averageScores: [],
      exceedScores: []
    };
    Object.assign(teachingQualityData, result);
    
    await nextTick();
    updateLineChart();
    updateBarChart();
  }
};

// 更新满意度分布饼图
const updatePieChart = () => {
  if (pieChart.value) {
    const data = satisfiDistrData.pieData.length > 0 ? satisfiDistrData.pieData : [];
    const colors = data.length > 0 ? data.map((item) => item.color) : pieData.map((item) => item.color);
    const satisfactionRate = satisfiDistrData.satisfactionRate || 0;
    
    const option = {
      color: colors,
      title: {
        text: satisfactionRate + "%",
        x: "center",
        y: "center",
        textStyle: {
          color: "#37DBFF",
          fontWeight: "bolder",
          fontSize: 30,
        },
      },
      legend: {
        show: false,
      },
      series: [
        {
          name: "外圈",
          type: "pie",
          radius: ["77%", "80%"],
          center: ["50%", "50%"],
          avoidLabelOverlap: false,
          padAngle: 5,
          label: {
            show: false,
            position: "center",
          },
          labelLine: {
            show: false,
          },
          data: data.length > 0 ? data : pieData,
        },
        {
          name: "内圈",
          type: "pie",
          radius: ["60%", "77%"],
          center: ["50%", "50%"],
          avoidLabelOverlap: false,
          padAngle: 5,
          itemStyle: {
            color: "rgba(255, 255, 255, 0.2)",
          },
          label: {
            show: false,
            position: "center",
          },
          labelLine: {
            show: false,
          },
          data: data.length > 0 ? data : pieData,
        },
      ],
    };
    
    // 使用notMerge: false来优化更新性能
    pieChart.value.setOption(option, false);
  }
};

// 更新学案评价图表
const updateXaChart = () => {
  if (pieChartA.value) {
    const option = {
      series: [
        // 刻度
        {
          type: "gauge",
          radius: "76%",
          startAngle: 360,
          endAngle: 0,
          axisTick: {
            show: true,
            lineStyle: {
              color: "#FFF",
              width: 2,
            },
            length: -8,
          }, //刻度样式
          splitLine: {
            show: false,
          }, //分隔线样式
          axisLabel: {
            show: false,
          }, //刻度节点文字颜色
          pointer: {
            show: false,
          },
          axisLine: {
            show: false,
          },
          label: {
            show: false,
          },
          detail: {
            show: false,
          },
        },
        {
          name: "内部进度条",
          type: "gauge",
          center: ["50%", "50%"],
          radius: "80%",
          splitNumber: 10,
          axisLine: {
            lineStyle: {
              color: [
                [
                  0.8,
                  new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                    {
                      offset: 0,
                      color: "#356bfd",
                    },
                    {
                      offset: 1,
                      color: "#69dce1",
                    },
                  ]),
                ],
                [1, "rgba(107,157,215,.25)"],
              ],
              width: 8,
            },
          },
          z: 4,
          axisLabel: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          splitLine: {
            show: false,
          },
          itemStyle: {
            color: "#45CAED",
          },
          detail: {
            show: false,
          },
          label: {
            show: false,
          },

          title: {
            //标题
            show: true,
            offsetCenter: [0, 0],
            textStyle: {
              color: "#37DBFF",
              fontSize: 28,
              lineHeight: 28,
            },
          },
          data: [
            {
              name: xaStatisData.satisfaction_rate + "%",
              value: parseFloat(xaStatisData.satisfaction_rate),
            },
          ],
          pointer: {
            show: false,
          },
        },
      ],
    };
    
    // 使用notMerge: false来优化更新性能
    pieChartA.value.setOption(option, false);
  }
};

// 更新学年统计图表
const updateYearChart = () => {
  if (chartA.value) {
    const xAxisData = yearStatData.xAxisData.length > 0 ? yearStatData.xAxisData : [
      "1月", "2月", "3月", "4月", "5月", "6月", 
      "7月", "8月", "9月", "10月", "11月", "12月"
    ];
    const seriesData = yearStatData.seriesData.length > 0 ? yearStatData.seriesData : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
    
    const option = {
      grid: {
        top: 40,
        right: 0,
        bottom: 50,
        left: 40,
      },
      tooltip: {
        formatter: function(params) {
          return `${params.name}<br/>满意率: ${params.value}%`;
        }
      },
      xAxis: {
        data: xAxisData,
        axisLine: {
          lineStyle: {
            color: "#0094ff", // ✅ X轴线颜色
          },
        },
        axisTick: {
          lineStyle: {
            color: "#0094ff", // ✅ X轴刻度线颜色
          },
        },
        axisLabel: {
          color: "#fff",
          fontSize: 10,
          rotate: 25, // 旋转标签以避免重叠
          interval: 0 // 显示所有标签
        },
      },
      yAxis: {
        type: "value",
        axisLine: {
          lineStyle: {
            color: "#00D1FF",
          },
        },
        splitLine: {
          lineStyle: {
            color: "#0094ff",
          },
        },
        axisLabel: {
          show: true,
          color: "#fff",
          formatter: '{value}%'
        },
      },
      series: [
        {
          type: "bar",
          barWidth: 14,
          data: seriesData,
          label: {
            show: true,
            position: "top",
            formatter: "{c}%",
            color: "#fff",
            fontSize: 10
          },
          itemStyle: {
            color: function (params) {
              return colorList[params.dataIndex % colorList.length];
            },
          },
        },
      ],
    };
    
    // 使用notMerge: false来优化更新性能
    chartA.value.setOption(option, false);
  }
};

// 更新平均分折线图
const updateLineChart = () => {
  if (lineChart.value) {
    const examNames = Object.keys(teachingQualityData.averageScores);
    const classNames = [];
    
    // 获取所有班级名称
    Object.values(teachingQualityData.averageScores).forEach(examData => {
      examData.forEach(item => {
        if (!classNames.includes(item.className)) {
          classNames.push(item.className);
        }
      });
    });
    
    // 如果没有数据，使用默认数据
    if (examNames.length === 0) {
      examNames.push("暂无数据");
      classNames.push("暂无班级");
    }
    
    const series = classNames.map(className => {
      const data = examNames.map(examName => {
        const examData = teachingQualityData.averageScores[examName];
        if (examData) {
          const classData = examData.find(item => item.className === className);
          return classData ? classData.averageScore : 0;
        }
        return 0;
      });
      
      return {
        name: className,
        type: "line",
        symbol: "circle",
        symbolSize: 6,
        data: data
      };
    });
    
    const option = {
      color: colorList,
      tooltip: {
        formatter: function(params) {
          return `${params.seriesName}<br/>${params.name}: ${params.value}分`;
        }
      },
      title: {
        text: "平均分",
        top: 20,
        textStyle: {
          color: "#00D1FF",
          fontSize: 10,
          lineHeight: 10,
        },
      },
      legend: {
        show: true,
        left: 'center',
        textStyle: {
          fontSize: 12,
          color: function (params) {
            return params.color;
          },
        },
      },
      grid: {
        top: 50,
        right: 10,
        bottom: 20,
        left: 30,
        containLabel: true,
      },
      xAxis: {
        data: examNames,
        axisLine: {
          lineStyle: {
            color: "#0094FF",
          },
        },
        axisTick: {
          lineStyle: {
            color: "#0094FF",
          },
        },
        splitLine: {
          lineStyle: {
            color: "#0094FF",
          },
        },
        axisLabel: {
          color: "#FFFFFF",
          fontSize: 10,
          rotate: 45
        },
      },
      yAxis: {
        axisLine: {
          lineStyle: {
            color: "#0094FF",
          },
        },
        axisLabel: {
          color: "#00D1FF",
          fontSize: 10,
          fontWeight: "bold",
        },
        splitLine: {
          lineStyle: {
            color: "#0094FF",
          },
        },
      },
      series: series
    };
    
    // 直接更新图表数据，避免重新初始化
    lineChart.value.setOption(option, true);
  }
};

// 更新超越得分柱状图
const updateBarChart = () => {
  if (barChart.value) {
    // 按考试名称分组，收集所有班级的超越得分数据
    const examGroups = {};
    const allClassNames = new Set(); // 收集所有班级名称
    
    teachingQualityData.exceedScores.forEach(item => {
      const examName = item.examName;
      if (!examGroups[examName]) {
        examGroups[examName] = {};
      }
      examGroups[examName][item.className] = item.exceedScore;
      allClassNames.add(item.className);
    });
    
    // 获取所有考试名称和班级名称
    const examNames = Object.keys(examGroups);
    const classNames = Array.from(allClassNames);
    
    // 如果没有数据，使用默认数据
    if (examNames.length === 0) {
      examNames.push("暂无数据");
      classNames.push("暂无班级");
    }
    
    // 为每个班级创建系列数据
    const series = classNames.map(className => {
      const data = examNames.map(examName => {
        // 如果该考试该班级有数据，使用真实数据；如果没有，使用0
        return examGroups[examName] && examGroups[examName][className] !== undefined 
          ? examGroups[examName][className] 
          : 0;
      });
      
      return {
        name: className,
        type: "bar",
        barWidth: 14,
        data: data,
        label: {
          show: true,
          position: "top",
          formatter: function(params) {
            // 只显示非0值的标签
            return params.value > 0 ? params.value : '';
          },
          color: "#fff",
          fontSize: 10
        },
        itemStyle: {
          color: function (params) {
            return colorList[params.dataIndex % colorList.length];
          },
        },
      };
    });
    
    const option = {
      color: colorList,
      title: {
        text: "超越得分",
        top: 20,
        textStyle: {
          color: "#00D1FF",
          fontSize: 10,
          lineHeight: 10,
        },
      },
      grid: {
        top: 50, // 与平均分图保持一致，确保图例对齐
        right: 10,
        bottom: 20,
        left: 30,
        containLabel: true,
      },
             legend: {
         show: false, // 隐藏图例
       },
      tooltip: {
        formatter: function(params) {
          return `考试: ${params.name}<br/>班级: ${params.seriesName}<br/>超越得分: ${params.value}`;
        }
      },
      xAxis: {
        data: examNames,
        axisLine: {
          lineStyle: {
            color: "#0094ff",
          },
        },
        axisTick: {
          lineStyle: {
            color: "#0094ff",
          },
        },
        axisLabel: {
          color: "#fff",
          fontSize: 10,
          rotate: 45
        },
      },
      yAxis: {
        type: "value",
        axisLine: {
          lineStyle: {
            color: "#00D1FF",
          },
        },
        splitLine: {
          lineStyle: {
            color: "#0094ff",
          },
        },
        axisLabel: {
          show: true,
          color: "#fff"
        },
      },
      series: series,
    };
    
    // 直接更新图表数据，避免重新初始化
    barChart.value.setOption(option, true);
  }
};

// 教学评价
let pieChartRef = ref(null);
let pieChart = ref(null);

// 学案评价
let pieChartRefA = ref(null);
let pieChartA = ref(null);

// 学年统计
let chartRefA = ref(null);
let chartA = ref(null);

// 班级均分与超越得分
let lineChartRef = ref(null);
let lineChart = ref(null);

let barChartRef = ref(null);
let barChart = ref(null);

const currentYearRange = ref([new Date(), new Date()]);

const rlt = reactive({
  // 学生排名情况
  stuRankInfo: {
    ranking: 0,
    sum_score: 0,
    total_num: 0,
  },
});

// 默认饼图数据（将被接口数据替换）
const pieData = [
  {
    name: "非常满意",
    value: 80,
    color: "#00FFB2",
  },
  {
    name: "满意",
    value: 10,
    color: "#00FFFF",
  },
  {
    name: "基本满意",
    value: 10,
    color: "#FBFF0D",
  },
  {
    name: "不满意",
    value: 10,
    color: "#FFFFFF",
  },
];

const initChartB = () => {
  const colors = satisfiDistrData.pieData.length > 0 
    ? satisfiDistrData.pieData.map((item) => item.color)
    : pieData.map((item) => item.color);
    
  const data = satisfiDistrData.pieData.length > 0 
    ? satisfiDistrData.pieData 
    : pieData;
    
  let satisfactionRate = satisfiDistrData.satisfactionRate || pieData[0].value;
  // 确保满意率显示为整数 - 直接抹去小数点，不四舍五入
  if (typeof satisfactionRate === 'number') {
    satisfactionRate = Math.floor(satisfactionRate);
  }
    
  pieChart.value = echarts.init(pieChartRef.value);
  pieChart.value.setOption({
    color: colors,
    title: {
      text: satisfactionRate + "%",
      x: "center",
      y: "center",
      textStyle: {
        color: "#37DBFF",
        fontWeight: "bolder",
        fontSize: 30,
      },
    },
    legend: {
      show: false,
    },
    series: [
      {
        name: "外圈",
        type: "pie",
        radius: ["77%", "80%"],
        center: ["50%", "50%"],
        avoidLabelOverlap: false,
        padAngle: 5,
        label: {
          show: false,
          position: "center",
        },
        labelLine: {
          show: false,
        },
        data: data,
      },
      {
        name: "内圈",
        type: "pie",
        radius: ["60%", "77%"],
        center: ["50%", "50%"],
        avoidLabelOverlap: false,
        padAngle: 5,
        itemStyle: {
          color: "rgba(255, 255, 255, 0.2)",
        },
        label: {
          show: false,
          position: "center",
        },
        labelLine: {
          show: false,
        },
        data: data,
      },
    ],
  });
};
// 学案评价
const initChartC = () => {
  const option = {
    series: [
      // 刻度
      {
        type: "gauge",
        radius: "76%",
        startAngle: 360,
        endAngle: 0,
        axisTick: {
          show: true,
          lineStyle: {
            color: "#FFF",
            width: 2,
          },
          length: -8,
        }, //刻度样式
        splitLine: {
          show: false,
        }, //分隔线样式
        axisLabel: {
          show: false,
        }, //刻度节点文字颜色
        pointer: {
          show: false,
        },
        axisLine: {
          show: false,
        },
        label: {
          show: false,
        },
        detail: {
          show: false,
        },
      },
      {
        name: "内部进度条",
        type: "gauge",
        center: ["50%", "50%"],
        radius: "80%",
        splitNumber: 10,
        axisLine: {
          lineStyle: {
            color: [
              [
                0.8,
                new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  {
                    offset: 0,
                    color: "#356bfd",
                  },
                  {
                    offset: 1,
                    color: "#69dce1",
                  },
                ]),
              ],
              [1, "rgba(107,157,215,.25)"],
            ],
            width: 8,
          },
        },
        z: 4,
        axisLabel: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          show: false,
        },
        itemStyle: {
          color: "#45CAED",
        },
        detail: {
          show: false,
        },
        label: {
          show: false,
        },

        title: {
          //标题
          show: true,
          offsetCenter: [0, 0],
          textStyle: {
            color: "#37DBFF",
            fontSize: 28,
            lineHeight: 28,
          },
        },
        data: [
          {
            name: xaStatisData.satisfaction_rate + "%",
            value: parseFloat(xaStatisData.satisfaction_rate),
          },
        ],
        pointer: {
          show: false,
        },
      },
    ],
  };
  pieChartA.value = echarts.init(pieChartRefA.value);
  pieChartA.value.setOption(option);
};

const colorList = ["#00FFF0", "#00FFB2", "#faff0d"];
const initChartA = () => {
  // 如果有数据，使用真实数据；否则使用默认数据
  const xAxisData = yearStatData.xAxisData.length > 0 ? yearStatData.xAxisData : [
    "1月", "2月", "3月", "4月", "5月", "6月", 
    "7月", "8月", "9月", "10月", "11月", "12月"
  ];
  const seriesData = yearStatData.seriesData.length > 0 ? yearStatData.seriesData : [120, 200, 150, 80, 70, 120, 200, 150, 80, 70, 120, 200];
  
  const option = {
    grid: {
      top: 30,
      right: 0,
      bottom: 30,
      left: 50,
      containLabel: false
    },
    tooltip: {
      formatter: function(params) {
        return `${params.name}<br/>满意率: ${params.value}%`;
      }
    },
    xAxis: {
      data: xAxisData,
      axisLine: {
        lineStyle: {
          color: "#0094ff", // ✅ X轴线颜色
        },
      },
      axisTick: {
        lineStyle: {
          color: "#0094ff", // ✅ X轴刻度线颜色
        },
      },
      axisLabel: {
        color: "#fff",
        fontSize: 10,
        rotate: 0, // 旋转标签以避免重叠
        interval: 0 // 显示所有标签
      },
    },
    yAxis: {
      type: "value",
      axisLine: {
        lineStyle: {
          color: "#00D1FF",
        },
      },
      splitLine: {
        lineStyle: {
          color: "#0094ff",
        },
      },
      axisLabel: {
        show: true,
        color: "#fff",
        formatter: '{value}%'
      },
    },
    series: [
      {
        type: "bar",
        barWidth: 14,
        data: seriesData,
        label: {
          show: true,
          position: "top",
          formatter: "{c}%",
          color: "#fff",
          fontSize: 10
        },
        itemStyle: {
          color: function (params) {
            return colorList[params.dataIndex % colorList.length];
          },
        },
      },
    ],
  };
  chartA.value = echarts.init(chartRefA.value);
  chartA.value.setOption(option);
};
const initChartE = () => {
  barChart.value = echarts.init(barChartRef.value);
  // 使用真实数据初始化超越得分图表
  updateBarChart();
};
function initChartD() {
  lineChart.value = echarts.init(lineChartRef.value);
  // 使用真实数据初始化平均分图表
  updateLineChart();
}
onMounted(() => {
  nextTick(() => {
    initChartA();
    initChartB();
    initChartC();
    initChartD();
    initChartE();

    window.addEventListener("resize", function () {
      pieChart.value.resize();
      pieChartA.value.resize();
      lineChart.value.resize();
      barChart.value.resize();
      chartA.value.resize();
    });
  })
  
  // 获取满意度排名数据
  getSatisfiRateData();
  // 获取学案评价数据
  getXaStatisData();
  // 获取满意度分布数据
  getSatisfiDistrData();
  // 获取学年统计数据
  getYearStatData();
  // 获取教学质量评价数据
  getTeachingQualityData();
});

// 监听路由参数变化，当工号改变时重新获取数据
watch(() => route.query.personCode, async (newPersonCode, oldPersonCode) => {
  if (newPersonCode && newPersonCode !== oldPersonCode) {
    // 清理旧教师的缓存数据，避免内存泄漏
    if (oldPersonCode) {
      const oldCacheKeys = [
        `satisfiRate_${oldPersonCode}`,
        `xaStatis_${oldPersonCode}`,
        `satisfiDistr_${oldPersonCode}`,
        `yearStat_${oldPersonCode}`,
        `teachingQuality_${oldPersonCode}`
      ];
      oldCacheKeys.forEach(key => dataCache.delete(key));
    }
    
    // 并行获取所有数据，避免串行延迟
    try {
      await Promise.all([
        getSatisfiRateData(),
        getXaStatisData(),
        getSatisfiDistrData(),
        getYearStatData(),
        getTeachingQualityData()
      ]);
    } catch (error) {
      console.error('获取数据失败:', error);
    }
  }
}, { immediate: true }); // 添加immediate: true，确保组件挂载时立即执行一次
</script>
<style scoped="studyContainer" lang="scss">
.chart-container {
  width: 100%;
  height: 100%;
}

.studyContainer {
  gap: 10px;
  height: 100%;

  .title {
    width: 100%;
    height: 20px;
    line-height: 20px;
    text-align: left;
    vertical-align: middle;
    border-left: 4px solid #00a7ff;
    padding-left: 10px;
    border-radius: 2px;
    margin-bottom: 5px;
  }

  .box1 {
    margin: 0px auto;
    box-sizing: border-box;
    width: 99%;
    height: 30%;

    .chengJJL-container {
      width: 100%;
      height: calc(100% - 25px);
      display: flex;
      flex-direction: column;
      gap: 2px;

      .chengJJL-item {
        flex: 30%;
        width: 100%;
        display: flex;
        gap: 2px;

        .chengJJL-itembox-left {
          flex: 30%;
          display: flex;
          align-items: center;
          justify-content: center;
          flex-direction: column;
          position: relative;

          .score {
            width: 100%;
            font-size: 65px;
            color: #00d1ff;
            text-align: center;
            text-transform: uppercase;
            letter-spacing: 10px;
            text-shadow: 5px 3px 6px rgba(0, 148, 255, 0.8),
              -2px -2px 4px rgba(255, 255, 255, 0.5);
            font-family: YSBiaoTiHei-regular;
            margin-top: 30px;
          }

          .score-p {
            color: #e5e5e5;
            font-family: "HarmonySansSC", sans-serif;
            font-size: 14px;
          }

          .score-img {
            position: absolute;
            top: -10px;
            right: 35px;
            width: 71px;
            height: 64px;
            /* border: 1px solid red; */
          }
        }

        .chengJJL-itembox-right {
          flex: 50%;
          padding: 0 30px;
        }

        .chengJJL-itembox {
          flex: 1;
          .s-title {
            color: #80d3ff;
            font-size: 14px;
          }
        }
      }
    }
  }

  .score-date {
    font-size: 12px;
    color: #00d1ff;
  }
}
:deep(.el-date-editor .el-range-input) {
  color: #00fff0 !important;
}
:deep(.el-date-editor.el-input__wrapper) {
  box-shadow: 0 0 0 1px #00fff0 inset;
}
:deep(.el-date-editor) {
  background: transparent !important;
}
:deep(.el-date-editor .el-range__icon) {
  color: #00fff0;
}
:deep(.el-date-editor .el-range-separator) {
  color: #00fff0;
}
.legend {
  border: 1px solid #00ffff;
  background: rgba(0, 255, 255, 0.2);
  padding: 6px 10px;
  border-radius: 10px;
  margin: 4px 0;
  font-size: 12px;
}
.legend-dot {
  width: 7px;
  height: 7px;
  border-radius: 50%;
  display: inline-block;
  margin-right: 6px;
}
.legend-a {
  border-bottom: 1px solid #00a372;
  font-size: 17px;
  text-align: center;
  color: #00d1ff;
  padding-bottom: 8px;
}
.legend-content {
  margin-top: 8px;
  font-size: 12px;
}


</style>
